//
//  CALFoodsViewController.m
//  CalCounter
//
//  Created by Toanpro on 9/9/13.
//  Copyright (c) 2013 Le thanh Lam. All rights reserved.
//

#import "CALFoodsViewController.h"
#import "CALFood.h"
#import "DataHelper.h"
#import "CALFoodAmountViewController.h"
#import "DateTimeView.h"
#import "CALAddNewFoodViewController.h"



@interface CALFoodsViewController ()<CALAddNewFoodViewControllerDelegate>{
    NSMutableArray *_foodsArray;
    __weak IBOutlet UITableView *_tableView;
    NSMutableArray *_searchArray;
//    NSMutableArray *_selectFoods;
    CALFood *_selectFood;
}
@end

@implementation CALFoodsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.isSearchMode = NO;
        // Custom initialization
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    _foodsArray = [[DataHelper sharedDatabase] getAllFoods];
    //    [self.searchDisplayController setActive:NO animated:NO];
    
    if([self.searchDisplayController isActive]){
        [self.navigationController setNavigationBarHidden:NO animated:NO];
        [self.searchDisplayController.searchBar becomeFirstResponder];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.foodName contains[c] %@",self.searchDisplayController.searchBar.text];
        _searchArray = [NSMutableArray arrayWithArray:[_foodsArray filteredArrayUsingPredicate:predicate]];
        [self.searchDisplayController.searchResultsTableView reloadData];
    }
    
    [_tableView reloadData];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addTapped:)];
    self.navigationItem.rightBarButtonItem = doneBtn;
    
    
    UIButton *titleLabel = [UIButton buttonWithType:UIButtonTypeCustom];
    [titleLabel setTitle:NSLocalizedString(@"selectfood", nil) forState:UIControlStateNormal];
    titleLabel.frame = CGRectMake(0, 0, 100, 44);
    titleLabel.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    [titleLabel addTarget:self action:@selector(titleTap:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.titleView = titleLabel;
    
//    _selectFoods = [NSMutableArray array];
    _foodsArray = [[DataHelper sharedDatabase] getAllFoods];
    [_tableView reloadData];
    
    if(self.isSearchMode){
        [self.searchDisplayController setActive:YES animated:YES];
        [self.searchDisplayController.searchBar becomeFirstResponder];
    }
    // Do any additional setup after loading the view from its nib.
}

- (void)titleTap:(id)sender{
    [_tableView setContentOffset:CGPointZero animated:YES];
}
- (void)addTapped:(id)sender{
    NSLog(@"CALFoodsViewController: Display the AddNewFoodViewController");
    CALAddNewFoodViewController *vc = [[CALAddNewFoodViewController alloc] initWithNibName:@"CALAddNewFoodViewController" bundle:nil];
    vc.delegate = self;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - CALAddNewFoodViewControllerDelegate

- (void)didAddNewFood:(CALFood *)food{
    [self.searchDisplayController setActive:YES animated:NO];
    self.searchDisplayController.searchBar.text = food.foodName;
    self.isSearchMode = YES;
//    [self.searchDisplayController setActive:YES animated:NO];
}

#pragma mark - UITableViewDelegate, UITableViewDatasource

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(tableView == _tableView)
        return [_foodsArray count];
    else
        return [_searchArray count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    
    CALFood *f = [(tableView == _tableView ? _foodsArray : _searchArray) objectAtIndex:indexPath.row];
    cell.textLabel.text = f.foodName;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%1.1f cals",f.cals];
    cell.imageView.image = [UIImage imageNamed:f.foodImage];
    [cell setAccessoryType:[_selectFood isEqual:f] ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    CALFood *f = [(tableView == _tableView ? _foodsArray : _searchArray) objectAtIndex:indexPath.row];
//    if([_selectFood isEqual:f])
//        return;
    
    if(_selectFood){
        NSInteger preIdx = [(tableView == _tableView ? _foodsArray : _searchArray) indexOfObject:_selectFood];
        if(preIdx != NSNotFound){
            UITableViewCell *preCell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:preIdx inSection:0]];
            [preCell setAccessoryType:UITableViewCellAccessoryNone];
        }
    }
    
    _selectFood = f;
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
    
    CALFoodAmountViewController *vc = [[CALFoodAmountViewController alloc] init];
    vc.selectedFood = _selectFood;
    NSArray *vcArray = [self.navigationController viewControllers];
    id eatingVc = [vcArray objectAtIndex:[vcArray count] - 2];
    vc.delegate = eatingVc;
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    CALFood *f = [(tableView == _tableView ? _foodsArray : _searchArray) objectAtIndex:indexPath.row];
    if(_selectFood == f)
        _selectFood = nil;
    [_foodsArray removeObject:f];
    [_searchArray removeObject:f];
    [[DataHelper sharedDatabase] deleteFood:f];
    [tableView reloadData];
}
#pragma mark - UISearchDisplayControllerDelegate

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.foodName contains[c] %@",searchString];
    _searchArray = [NSMutableArray arrayWithArray:[_foodsArray filteredArrayUsingPredicate:predicate]];
    return YES;
}

- (void)searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller{
    [_tableView reloadData];
}


#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    if ([_searchArray count] == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:NSLocalizedString(@"AddNewFood", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"No", nil) otherButtonTitles:NSLocalizedString(@"Yes", nil), nil];
        [alert show];
    }
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex != 0) {
        CALAddNewFoodViewController *vc = [[CALAddNewFoodViewController alloc] initWithNibName:@"CALAddNewFoodViewController" bundle:nil withFoodName:self.searchDisplayController.searchBar.text];
        [self.navigationController pushViewController:vc animated:YES];
    }
}







@end
